import React, {forwardRef, useEffect, useImperativeHandle, useState} from "react";
import { Button, Modal, Space, Table, TableColumnType, message } from "antd";
import { lineQuoteTypes  } from "@/constants/types";
import { fetchLineQuoteList, lpsLineQuoteOffSale, lpsLineQuoteOnSale, updateLpsLineQuote } from "../services";
import { calculateTableWidth } from "@/utils/util";
import XlTableDictColumn from "@/components/Table/XlTableDictColumn";
import LineQuoteUpdate from "../modals/LineQuoteUpdate";
import { useRequest } from "ahooks";

interface tabProps {
  searchValue: any;
  activeKey: string;
  tabKey: string,
  refreshNum: Function
}
const LineQuoteTable = forwardRef(({searchValue = {}, activeKey, tabKey, refreshNum}: tabProps, ref) => {
  const [dataSource, setDataSource] = useState([]);
  const [pagination, setPagination] = useState({
    pageNum: 1,
    pageSize: 50,
    total: 0
  });
  const [visible, setVisible] = useState<boolean>(false);
  const [currentRow, setCurrentRow] = useState<lineQuoteTypes | null>(null);
  const {loading: updateLoading, runAsync: updateLpsLineQuoteApi} = useRequest(updateLpsLineQuote, {manual: true});

  // 
  const [selectedRowKeys, setSelectedRowKeys] = useState<string[]>([]);
  const [selectedRows, setSelectedRows] = useState<lineQuoteTypes[]>([]);



  const search = async (params:{pageNum: number; pageSize: number} = {
    pageNum: 1,
    pageSize: 10
  }) => {
    const res = await fetchLineQuoteList({
      ...searchValue,
      ...params,
    });
    setDataSource(res?.data || []);
    setPagination({
      ...params,
      total: res?.total
    });
  }

  const rowSelection = {
    selectedRowKeys,
    onChange: (keys: string[], rows: lineQuoteTypes []) => {
      setSelectedRowKeys(keys);
      setSelectedRows(rows);
    },
  };

  const getSelections = () => {
    return {
      selectedRowKeys,
      selectedRows
    };
  }

  const refreshTable = () => {
    if (activeKey !== tabKey) {
      return ;
    }
    search({
      pageNum: 1,
      pageSize: 10
    });
  }

  useImperativeHandle(ref, () => ({
    getSelections,
    refreshTable
  }));


  useEffect(() => {
    if (tabKey === activeKey) {
      search({
        pageNum: pagination.pageNum,
        pageSize: pagination.pageSize
      });
    }
  }, [tabKey, activeKey, JSON.stringify(searchValue)]);

  // 上架
  const handlePut = (record: lineQuoteTypes) => {
    Modal.confirm({
      title: '上架提醒',
      content: '是否确定上架？',
      onOk: () => {
        lpsLineQuoteOnSale({ids: [record?.id]}).then(
          res => {
            if (res?.code === '0') {
              message.success('上架成功');
              search({
                pageNum: 1,
                pageSize: 10
              });
              refreshNum();
            } else {
              message.warning(res?.msg || '上架失败!');
            }
          }
        )
      }
    });
  }
  // 下架
  const handleOff = (record: lineQuoteTypes) => {
    Modal.confirm({
      title: '停售提醒',
      content: '是否确定停售？',
      onOk: () => {
        lpsLineQuoteOffSale({ids: [record?.id]}).then(
          res => {
            if (res?.code === '0') {
              message.success('停售成功');
              search({
                pageNum: 1,
                pageSize: 10
              });
              refreshNum();
            } else {
              message.warning(res?.msg || '停售失败!');
            }
          }
        )
      }
    });
  }
  // 更新报价
  const lineQuoteUpdateProps = {
    title: '更新报价',
    visible,
    currentRow,
    loading: updateLoading,
    onCancel: () => {
      setVisible(false);
      setCurrentRow(null);
    },
    onSubmit: async (params: lineQuoteTypes) => {
      const res = await updateLpsLineQuoteApi(params);
      if (res?.code === '0') {
        lineQuoteUpdateProps.onCancel();
        search({
          pageNum: 1,
          pageSize: 10
        });
        refreshNum();
      }
    }
  }
  const handleEdit = (record: lineQuoteTypes) => {
    setCurrentRow(record);
    setVisible(true);
  }

  const columns: TableColumnType<lineQuoteTypes> [] = [
    {
      title: '售卖状态',
      dataIndex: 'saleStatus',
      width: 120,
      render: (_, record: lineQuoteTypes) => <XlTableDictColumn type="saleStatus" value={record?.saleStatus} />
    },
    {
      title: '年份',
      dataIndex: 'year',
      width: 100,
      render: (_, record) => <XlTableDictColumn type="year" value={record?.year} />
    },
    {
      title: '周次',
      dataIndex: 'week',
      width: 100
    },
    {
      title: '国家',
      dataIndex: 'country',
      width: 100,
      render: (_, record) => <XlTableDictColumn type="country" value={record?.country} />
    },
    {
      title: '产品名称',
      dataIndex: 'product',
      width: 100,
      render: (_, record) => <XlTableDictColumn type="prdType" value={record?.product} />
    },
    {
      title: '起始地',
      dataIndex: 'sport',
      width: 120,
      render: (_, record) => <XlTableDictColumn type="sport" value={record?.sportCode} />
    },
    {
      title: '目的港',
      dataIndex: 'dport',
      width: 120,
      render: (_, record) => <XlTableDictColumn type="dport" value={record?.dportCode} />
    },
    {
      title: '目的地类型',
      dataIndex: 'destType',
      width: 120,
      render: (_, record) => <XlTableDictColumn type="destType" value={record?.destType} />
    },
    {
      title: '目的地',
      dataIndex: 'destCode',
      width: 120
    },
    {
      title: '卖价CBM/元',
      dataIndex: 'cbmPrice',
      width: 120
    },
    {
      title: '卖价KGS/元',
      dataIndex: 'kgsPrice',
      width: 120
    },
    {
      title: '赔付价CBM/元',
      dataIndex: 'lowestCbmPrice',
      width: 140
    },
    {
      title: '赔付价KGS/元',
      dataIndex: 'lowestKgsPrice',
      width: 140
    },
    {
      title: '拼箱方式',
      dataIndex: 'groupType',
      width: 120,
      render: (_, record) => <XlTableDictColumn type="groupType" value={record?.groupType} />
    },
    {
      title: '派送方式',
      dataIndex: 'deliveryMethod',
      width: 120,
      render: (_, record) => <XlTableDictColumn type="deliveryMethod" value={record?.deliveryMethod} />
    },
    {
      title: '最低起收',
      dataIndex: 'minTakeCbm',
      ellipsis: true,
      width: 200,
      render: (_, record) => {
        return (
          <Space>
            <span>CBM: {record?.minTakeCbm};</span>
            <span>KGS: {record?.minTakeKgs};</span>
          </Space>
        );
      }
    },
    {
      title: '参考时效/天',
      dataIndex: 'referenceTimeliness',
      width: 120
    },
    {
      title: '赔付时效',
      dataIndex: 'failTimeliness',
      width: 120
    },
    {
      title: '收货仓库',
      dataIndex: 'cwhName',
      width: 150
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime',
      width: 180
    },
    {
      title: '操作',
      dataIndex: 'options',
      width: 180,
      fixed: 'right',
      render: (_, record) => {
        const btns: any = {
          1: <Button type="link" key="上架" onClick={() => handlePut(record)}>上架</Button>,
          2: <Button type="link" key="停售" onClick={() => handleOff(record)}>停售</Button>,
          3: <Button type="link" key="重新上架" onClick={() => handlePut(record)}>重新上架</Button>
        };
        return (
          <Space>
            {btns?.[record?.saleStatus]}
            <Button type="link" key="编辑" onClick={() => handleEdit(record)}>编辑</Button>
          </Space>
        );
      }
    }
  ];

  return (
    <>
      <Table
         bordered
         rowKey="id"
         dataSource={dataSource}
         columns={columns}
         scroll={{x: calculateTableWidth(columns), y:560}}
         rowSelection={rowSelection}
         pagination= {{
          showTotal: total => `共 ${total} 条`,
          ...pagination,
          onChange: (pageNum, pageSize) => {
            search({pageNum, pageSize});
          }
         }}
      /> 
      {visible && <LineQuoteUpdate {...lineQuoteUpdateProps} />}
    </>
  );
});


export default LineQuoteTable;